package com.bridgeintelligent.tag.interceptors;

import com.bridgeintelligent.tag.annotations.Resubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：liwei
 * @Date：2023/9/21
 * @Desc： 防重复提拦截器工具类
 */
@Slf4j
@Component
public class ResubmitInterceptor implements HandlerInterceptor {
    // key: 固定前缀
    private static final String FIXED_SESSION = "repeatData";
    private static final String DEL_FLAG = "DEL_FLAG";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            log.info("=========================>你被拦截了");
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                // 请求方法
                Method method = handlerMethod.getMethod();
                // 获取自定义注解-防重复注解(@Resubmit)
                Resubmit annotation = method.getAnnotation(Resubmit.class);
                // 判断方法是否添加自定义注解(@Resubmit)
                if (annotation != null) {
                    //如果重复相同数据
                    if (repeatDataValidator(request)) {
                        // 自定义返回结果类
                        Map<String,Object> result = new HashMap<>();
                        result.put("code", 999);
                        result.put("msg",annotation.messge());

                        // 设置字符集编码
                        response.setCharacterEncoding("utf-8");
                        response.getWriter().write(JSON.toJSONString(result));
                        return false;
                    } else {
                        return true;
                    }
                }
                return true;
            } else {
                return true;
            }
        } catch (IOException e) {
            log.error("防重复提拦截器工具类异常", e);
            return false;
        }
    }


    /**
     * 验证同一个url数据是否相同提交,相同返回true
     *
     * @param request
     * @return
     */
    private boolean repeatDataValidator(HttpServletRequest request) {
        // 获取POST请求体-body-入参
//        String params = getRequestBodyParam(request);
        String params = JSON.toJSONString(request.getParameterMap());
        Map<String, String> map = new HashMap<>();
        // 组装Map key: url、 value:url+请求方法体+时间
        map.put(request.getRequestURI(), params);
        String nowUrlParams = JSON.toJSONString(map);
        log.info("=========>本次请求参数【nowUrlParams】：{}", nowUrlParams);
        Object preUrlParams = request.getSession().getAttribute(FIXED_SESSION);
        log.info("=========>上一次请求参数【preUrlParams】：{}", preUrlParams);

        //如果上一个数据为null,表示还没有访问页面
        if (preUrlParams == null) {
            //如果上一个数据为null,表示还没有访问页面
            request.getSession().setAttribute(FIXED_SESSION, nowUrlParams);
            return false;
        } else {
            //如果上次url+数据和本次url+数据相同，则表示重复添加数据
            if (preUrlParams.equals(nowUrlParams)) {
                log.error("======>[请求频繁提交 repeatDataValidator URL :{}; param :{}]", request.getRequestURI(), params);
                request.getSession().setAttribute(DEL_FLAG, "1");
                return true;
            } else {
                //如果上次 url+数据 和本次url加数据不同，则不是重复提交
                request.getSession().setAttribute(FIXED_SESSION, nowUrlParams);
                return false;
            }

        }
    }


    /**
     * 获取请求体-body-入参
     *
     * @param request
     * @return
     */
    private String getRequestBodyParam(HttpServletRequest request) {
        BufferedReader bufferedReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {


            bufferedReader = request.getReader();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                stringBuffer.append(str);
            }
            bufferedReader.close();
        } catch (IOException e) {
            log.error("解析入参异常！！！", e);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    log.error("解析入参异常！！！", e);
                }
            }
        }
        log.info("=====>解析入参:{}",stringBuffer);
        return stringBuffer.toString();
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
        HttpSession session = request.getSession();
        if(StringUtils.isNotEmpty((String)request.getSession().getAttribute(DEL_FLAG))){
            session.removeAttribute(FIXED_SESSION);
            session.removeAttribute(DEL_FLAG);
            log.info("================>删除入参:{}",FIXED_SESSION);
        }

    }
}
